<template>
    <div class="mainBox">
        <!-- <div>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item
                    ><span style="font-size: 14px;"
                        >智提升</span
                    ></el-breadcrumb-item
                >
                <el-breadcrumb-item>同步</el-breadcrumb-item>
                <el-breadcrumb-item>练习</el-breadcrumb-item>
                <el-breadcrumb-item>
                    <span style="font-size: 14px;">开始练习</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div> -->
        <div class="title">开始练习</div>

        <div v-for="(question, index) in questionList" :key="index">
            <answer-card
                ref="answercard"
                v-if="index == swiperCurrent"
                :question="question"
                :questionTotal="questionTotal"
                :lastPage="lastPage"
                :currentPage="currentPage"
                :subQuestionObj="
                    subQuestionObj.filter(
                        item => item.name == question.question_id
                    )
                "
                :subAnswerLog="
                    subAnswerLog.filter(
                        item1 => item1.name == question.question_id
                    )
                "
                :isAnswerLog="isAnswerLog"
                :index="index"
                :len="questionListLen"
                :f_len="questionListLen"
                :practice_lists_count="practice_lists_count"
                :practice_id="practice_id"
                :swiperCurrent="swiperCurrent"
                :f_swiperCurrent="swiperCurrent"
                :title="title"
                :section_name="section_name"
                @setIndex="setIndex"
                @setAnswerLog="setAnswerLog"
                @setSubAnswerLog="setSubAnswerLog"
                @setErrorReason="setErrorReason"
                @setStar="setStar"
                @getPropUp="dialog1Show"
                @getPrize="getPrize"
            ></answer-card>
        </div>
        <dialog1
            ref="dialog1"
            v-if="isShowLearningSituation"
            @confirm="confirm"
        ></dialog1>
        <dialog2 ref="dialog2" v-if="credit"></dialog2>
    </div>
</template>

<script>
import dialog1 from "@/components/dialog1/index";
import dialog2 from "@/components/dialog2/index";
import answerCard from "./answerCard/index";
import {
    getQuestionList,
    getQuestionSubList
} from "@/api/testQuestions/question";
import { practiceAdd, practiceAnswerLog } from "@/api/testQuestions/practice";
import { latex_reques, latex_answer } from "@/utils/latex";
// import { addPracticeTrainError } from "@/api/testQuestions/practiceTrainError";
import { practiceTrainTime } from "@/api/testQuestions/practiceTrainTime";
import { practiceTrainDetail } from "@/api/testQuestions/practiceTrainDetail";
export default {
    components: {
        dialog1,
        dialog2,
        answerCard
    },
    props: {},
    data() {
        return {
            zid: null, // 章节ID
            sid: null, // 科目ID
            fid: null, // 父章节ID
            questionPage: 1, // 当前题目列表页码,默认为1
            questionTotal: 0, // 该章节的题目总数
            questionList: [], // 题目列表
            questionListLen: 0, // 练习记录的题目总数
            currentPage: 0, ///题目当前页数
            practice_lists_count: 0, // 该章节下的练习进度
            swiperCurrent: 0, //题目进度
            practice_id: null, // 记录id
            lastPage: 0, //题目最大页数
            isAnswerLog: false, //是否已经作答
            practice_type: 1, //是否知识点答题
            is_err: false, // 错因状态 true表示答错，false表示答对，则不会显示错因
            isState: false, // 错因话题状态，true表示已勾选，false表示未勾选
            loading: null, //加载
            isShowLearningSituation: false, //是否显示今日学情
            credit: false, // 获得学情分时弹出学情分
            title: "", //章节标题
            section_name: "", //章节名称
            prizeArr: [], // 获得奖章列表
            temp_prizeArr: [], // 临时存储学情分和勋章的状态
            subQuestionObj: [], //子试题列表
            subAnswerLog: [] // 子题目答案记录
        };
    },
    computed: {},
    watch: {},
    beforeCreate() {
        // 生命周期钩子：组件实例刚被创建，组件属性计算之前，如 data 属性等
    },
    created() {
        // 生命周期钩子：组件实例创建完成，属性已绑定，但 DOM 还未生成，el 属性还不存在
        // 初始化渲染页面
    },
    beforeMount() {
        // 生命周期钩子：模板编译/挂载之前
    },
    mounted() {
        // 生命周期钩子：模板编译、挂载之后（此时不保证已在 document 中）
        this.fid = this.$route.query.fid; // 父章节ID
        this.zid = this.$route.query.zid; // 章节ID
        this.sid = this.$route.query.sid; // 科目ID
        this.title = this.$route.query.title; //章节标题
        this.section_name = this.$route.query.section_name; //章节名称
        this.practice_id = Number(this.$route.query.practice_id);
        if (this.$route.query.practice_lists_count) {
            this.swiperCurrent = Number(this.$route.query.practice_lists_count);
        }
        this.practice_lists_count = Number(
            this.$route.query.practice_lists_count
        );
        this.getQuestionList();
    },
    methods: {
        // 今日学情展示
        dialog1Show() {
            if (this.prizeArr.length > 0) {
                this.temp_prizeArr = this.prizeArr;
                this.prizeArr = [];
            }
            this.isShowLearningSituation = true;
        },
        dialog3Show() {
            this.$refs.dialog3.dgShow();
        },
        // 赋值 父组件赋值
        setSubjectData(index, data) {
            this.subjectList[index] = data;
            console.log("赋值", this.subjectList);
        },
        //设置题目索引
        setIndex(index) {
            this.swiperCurrent = index;
            if (this.questionList[this.swiperCurrent].answerLog) {
                this.isAnswerLog = true;
            } else {
                this.isAnswerLog = false;
            }
        },
        /* 获取所有试题 */
        // 获取试题
        getQuestionList() {
            var da = {
                is_get_answer: 2, // 1为不获取答案，2为获取答案
                page: this.questionPage, // 页码，默认为1
                pagesize: 8,
                is_out_html: 2 // 1不过滤标签，2为过滤
                // sid: 145	// 科目id
            };
            if (this.zid != undefined) {
                da.zid = this.zid;
            }
            getQuestionList(da)
                .then(async res => {
                    if (res.code === 200) {
                        this.questionTotal = res.data.total;
                        let questionList = res.data.data,
                            parentQuestionIdList = [];

                        questionList.forEach(item => {
                            if (item.is_sub_question === 2) {
                                item.answer_list = [];
                                parentQuestionIdList.push(item.question_id);
                                // this.$set(this.spreadHeightObj, index, 0)
                            }
                        });
                        if (parentQuestionIdList.length) {
                            // 获取子题列表
                            var data = {
                                parent_question_id: parentQuestionIdList.join(
                                    ","
                                ),
                                is_get_answer: 2
                            };
                            await getQuestionSubList(data).then(res => {
                                if (res.code === 200) {
                                    let subQuestionList = res.data;
                                    this.latexFilter(subQuestionList);
                                    subQuestionList.forEach(item =>
                                        this.subQuestionObj.push({
                                            name: item.f_question_id,
                                            data: item.question_sub_lists
                                        })
                                    );
                                }
                            });
                        }

                        this.latexFilter(questionList);

                        this.questionList = questionList;
                        // 设置错误原因是否显示
                        this.questionList.forEach(item => {
                            item.isShowError = true;
                        });
                        this.questionListLen = res.data.question_ids_count;
                        console.log("练习记录的题目总数", this.questionListLen);
                        this.lastPage = res.data.last_page;
                        this.currentPage = res.data.current_page;
                        console.log("currentPage", this.currentPage);
                        console.log("问题", this.questionList);
                        // this.getSeniorResource(
                        //     this.questionList[this.swiperCurrent].question_id
                        // );
                        // if(this.questionList[this.swiperCurrent].is_sub_question == 1) {
                        // 	this.getSeniorResource(this.questionList[this.swiperCurrent].question_id)
                        // } else {
                        // 	var ques_id = Number(this.questionList[this.swiperCurrent].question_id);
                        // 	setTimeout(() => {
                        // 		this.getSeniorResource(this.subQuestionObj[ques_id][0].question_id)
                        // 	},800)
                        // }

                        if (this.practice_lists_count >= this.questionListLen) {
                            this.swiperCurrent = 0;
                        }
                    } else {
                        this.$message.error("该章节还没有题目");
                        this.$router.back(-1);
                    }
                })
                .then(async () => {
                    // this.practice_lists_count === 99 && this.questionListLen !== 0	// 未创建过练习 且 该章节有题目 则创建练习
                    if (!this.practice_id) {
                        // 创建练习
                        // 文档：https://www.showdoc.cc/416494108281686?page_id=2514406164294397
                        let obj = {
                            chapterid: this.zid, // 章节ID
                            subjectid: this.sid, // 科目ID
                            question_num: this.questionListLen, // 试题数量
                            fid: this.fid, // 父章节id
                            practice_page: this.questionPage, // 题目页数
                            practice_type: this.practice_type // 是否知识点答题
                        };
                        await practiceAdd(obj).then(res => {
                            this.practice_lists_count = 0;
                            this.practice_id = Number(res.data.practice_id);
                            console.log("练习id", this.practice_id);
                        });
                    } else {
                        // 练习历史答案
                        // 文档：https://www.showdoc.cc/416494108281686?page_id=2873748434599508
                        await practiceAnswerLog({
                            practice_id: this.practice_id
                        }).then(res => {
                            let answerLogList = res.data;
                            answerLogList.forEach((item, index) => {
                                this.questionList[index].answerLog = item;
                                // 设置错误原因隐藏
                                this.questionList[index].isShowError = false;
                                // 获取每道题的答题时间
                                practiceTrainTime({
                                    question_id: this.questionList[index]
                                        .question_id, // 试题ID
                                    practice_id: this.practice_id // 记录ID
                                }).then(res => {
                                    this.questionList[index].answerLog.mySpent =
                                        res.data.train_time;
                                });
                                // 获取每道题的评星个数
                                practiceTrainDetail({
                                    question_id: this.questionList[index]
                                        .question_id, // 试题ID
                                    practice_id: this.practice_id // 记录ID
                                }).then(res => {
                                    // 返回400表示也没有评星，那么也要给个默认值
                                    if (res.data.code == 400) {
                                        this.questionList[
                                            index
                                        ].answerLog.star = 0;
                                    } else {
                                        // 拿到评星和用时，如果拿不到就默认给个-1 以便子组件可以监听到
                                        this.questionList[
                                            index
                                        ].answerLog.star = res.data.star_num;
                                    }
                                });
                                if (item.is_sub_question === 2) {
                                    this.subAnswerLog.push({
                                        name: item.question_id,
                                        data: item.sub_question
                                    });
                                    console.log("历史答案", this.subAnswerLog);
                                }
                            });
                        });
                    }
                });
        },
        // 解析试题
        latexFilter(obj) {
            /**
             * @param {Object} 试题列表
             * @param {String} json对象 key 名
             **/
            latex_reques(obj, "question_title"); // 解析 试题标题 latex 公式转换
            latex_reques(obj, "question_analysis"); // 解析 试题解析 latex 公式转换
            latex_answer(obj, "answer_list"); // 解析答案选项 latex 公式转换
        },
        // // 更新该章节下的练习进度
        // slither(e) {
        //     this.practice_lists_count += 1;
        //     this.$nextTick(() => {
        //         // 获得奖励的弹窗
        //         let prizeLen = this.prizeArr.length;
        //         if (prizeLen >= 2) {
        //             this.various = "various";
        //             this.gain = true;
        //         } else if (prizeLen === 1) {
        //             this.various = "medal";
        //             this[this.prizeArr[0]] = true;
        //         }

        //         this.prizeArr = []; // 重置奖励弹窗
        //     });
        // },
        setAnswer(obj) {
            this.isAnswer = obj.isAnswer;
            // 获取当前这道题是否属于子题
            this.isSubQuestion = obj.isSubQuestion;
        },
        // 设置历史答案
        setAnswerLog(data, mySpent) {
            console.log("data>>>>>>>>", data);
            this.questionList[this.swiperCurrent].answerLog = data;
            this.questionList[this.swiperCurrent].answerLog.mySpent = mySpent;
        },
        // 设置子试题历史答案
        setSubAnswerLog(question_id, childIndex, data) {
            this.subQuestionObj.forEach(item => {
                if (item.name == question_id) {
                    item.data.forEach((item1, index1) => {
                        if (index1 == childIndex) {
                            item1.answerLog = data;
                        }
                    });
                }
            });
        },
        // 设置错误原因
        setErrorReason(error_id, isShowError) {
            console.log("错误原因id", error_id);
            this.questionList[this.swiperCurrent].isShowError = isShowError;
            this.questionList[this.swiperCurrent].answerLog.error_id = error_id;
        },
        // 设置错误原因
        setStar(star) {
            this.questionList[this.swiperCurrent].answerLog.star = star;
        },
        // 获得奖励
        getPrize(prize) {
            this.prizeArr.push(prize);
        },
        // 今日学情确定事件，当点击后，还需要拿临时存储勋章的数组判断是否有勋章弹窗
        confirm() {
            this.isShowLearningSituation = false;
            if (this.temp_prizeArr.length <= 0) return;
            this.temp_prizeArr.forEach(item => {
                if (item === "credit") this.credit = true;
            });
            // 最后在把临时的状态重新清空
            this.temp_prizeArr = [];
        }
    }
};
</script>

<style lang="scss" scoped>
.mainBox {
    width: 100%;
    padding: 26px;
    box-sizing: border-box;
    .title {
        font-size: 20px;
        color: #2d3440;
        margin-top: 20px;
        margin-bottom: 20px;
    }
}
</style>
